#!/bin/sh
ROOT_UID=0

if [ "$UID" -eq "$ROOT_UID" ]
then
  echo "can not run with root."
  exit 1
fi

ACTION=$1

usage()
{
        echo "usage: `deploy.sh $0` pro|test|dev"
}
MAVEN_ENV=$2
if [ $# -ne 1 ]; then
        usage
        exit 1
fi
case $MAVEN_ENV in
        pro|test|dev) echo "maven evn is $MAVEN_ENV"
        ;;
        *)usage
        exit 1
        ;;
esac

APP_PNAME=house
APP_PORT=8086
CODE_HOME=/home/admin/code/${APP_PNAME}
PACKAGE_HOME=/home/admin/code/${APP_PNAME}
INSTALL_COMMAND="mvn clean install -Dmaven.test.skip=true -P$MAVEN_ENV"
PACKAGE_COMMAND="mvn clean package -Dmaven.test.skip=true -P$MAVEN_ENV"
JAR_NAME=${APP_PNAME}-exec.jar
WORK_HOME=/home/admin/work/${APP_PNAME}

APP_CHECK_URL="http://127.0.0.1:${APP_PORT}/appcheck.htm"

mkdir -p ${PACKAGE_HOME}
mkdir -p ${WORK_HOME}

update_code() {
    echo "update code...."
    cd $CODE_HOME
    git pull
    STATUS=$?
    if [ "$STATUS" -ne "0" ]; then
            echo >&2 "git pull failed with $STATUS"
            exit 1
    fi
}

stop_app() {
    echo "stop server...."
    sleep 1

    ps aux | grep -v grep | grep "$APP_PNAME" > /dev/null
    STATUS=$?
    if [ "$STATUS" -eq "0" ]; then
        echo "kill $APP_PNAME."
        ps ax | grep "$APP_PNAME" | grep -v grep | awk '{print $1}'| xargs kill
    fi
}

compile() {
    cd ${CODE_HOME}
    ${INSTALL_COMMAND}

    STATUS=$?
    if [ "$STATUS" -eq "0" ]; then
            echo "maven deploy successful"
    else
            echo >&2 "Deployment Failed"
            exit 1
    fi
}


start_app(){
    rm -rf ${WORK_HOME}/${JAR_NAME}

    cp ${PACKAGE_HOME}/${JAR_NAME} ${WORK_HOME}/${JAR_NAME}

    echo "start server...."

    nohup ${JAVA_HOME}/bin/java -jar ${JAR_NAME} --spring.profiles.active=${MAVEN_ENV} &

    STATUS=$?
    if [ "$STATUS" -eq "0" ]; then
            echo "server run successful"
    else
            echo >&2 "server run failed"
            exit 1
    fi

    sleep 1
}

check_status(){
    echo "start check app port $APP_PORT"
    i=0
    while :
    do
      stillRunning=$(netstat -an|grep LISTEN|egrep "${APP_PORT}" |grep -v "grep")
      if [ "$stillRunning" ] ; then
        echo "port bind success.."
        break
      else
        ((i++));
        echo "wait port bind...${i}"
      fi
      sleep 1
    done

    echo "start check app url $APP_CHECK_URL"

    i=0
    while :
    do
      httpstatus=$(curl  -m 10 -o /dev/null -s -w %{http_code} "${APP_CHECK_URL}")
      if [ "$httpstatus" -eq "200" ] ; then
        echo "server start success.."
        break
      else
        ((i++));
        echo "wait server start...${i} current return status ${httpstatus}"
      fi
      sleep 1
    done
}


start() {
    update_code
    compile
    start_app
    check_status
}
stop() {
    stop_app
}
case "$ACTION" in
    start)
        start
    ;;
    stop)
        stop
    ;;
    restart)
        stop
        start
    ;;
    *)
        usage
    ;;
esac
